/**
 下方按钮操作行： A ♫ @ ＋
 */
import React, {Component} from 'react';
import * as mobx from 'mobx';
import {inject, observer} from 'mobx-react';
import {Flex, Icon, Toast, Popover} from 'weaver-mobile';
import {Browser, AtSomeone, Upload, Signature} from 'weaver-mobile-page';
import {withRouter} from 'react-router-dom';
import * as SignUtil from '../../util/SignUtil';
import * as VariableKeys from '../../constants/variableKey';
import * as AdapterConstant from '../../constants/adapter';
import base from "../../util/base";
import {checkRemark} from "../../util/SignUtil";
import {getVariableMapVal} from "../../util/SignUtil";
import jQuery from 'jquery';

const Item = Popover.Item;

@inject('wfSignInputStore')
@withRouter
@observer
export class IconBtnsList extends Component {
    componentDidMount(){
        jQuery('.wm-signature').removeClass('wm-browser');
    }
    componentDidUpdate(){
        jQuery('.wm-signature').removeClass('wm-browser');
    }
    render() {
        const {history, wfSignInputStore} = this.props;
        const {batchControlVariableMap, controlVariableMap, variableMap, atUserStore, Adapter, isForwad, signatureRoute} = wfSignInputStore;


        const signVoiceEntry = SignUtil.getVariableMapVal(VariableKeys.SIGN_VOICE_ENTRY, false);
        const showAttachment = SignUtil.getVariableMapVal(VariableKeys.SHOW_MORE_FUN, false);

        const wfOperateStore = base.wfOperateStore;
        const {markInfo = {}} = wfOperateStore;
        const signParams = mobx.toJS(markInfo);
        const {isSignDoc_edit = false, isSignWorkflow_edit = false, isannexupload_edit = false, annexsecId = ''} = signParams;

        const {remarkInfo={}}=markInfo;
        let value = isForwad ? (variableMap.get(VariableKeys.FORWARD_SIGN_HANDWRITTEN+"_datasAndUrls")||{}) : (variableMap.get(VariableKeys.SIGN_HANDWRITTEN+"_datasAndUrls")||{})
        const {modeType={}}=value;
        const { handwritingType="h5" } = remarkInfo;
        const handlewritingKey = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;
        const localExist = SignUtil.getVariableMapVal("localExist", false)
        const isEm = handwritingType=="em"&&(window.em&&window.em.checkJsApi&&window.em.checkJsApi("handleWriting"));

        return (
            <div className='sign-action-btns'>
                <Flex className='sign-action-list' justify="around" align='center'>
                    {Adapter.judgeApiSupport(AdapterConstant.API_SPEECH_TO_TEXT) &&
                        <div className={'sign-icon-item'} onClick={() => {
                            // Adapter.speechTotext();
                            let updateParams = {};
                            updateParams[VariableKeys.SIGN_VOICE_ENTRY] = !signVoiceEntry;
                            updateParams[VariableKeys.SHOW_MORE_FUN] = false;
                            updateParams[VariableKeys.SIGN_IMG_UPLOAD] = false;
                            batchControlVariableMap(updateParams)
                        }}>
                            <Icon style={{'color': signVoiceEntry ? '#2DB7F5' : ''}} type={'voice'}/>
                        </div>
                    }
                    <div className={'sign-icon-item'} onClick={() => {}}>
                    <Signature
                        store={signatureRoute}
                        value={mobx.toJS(value)}
                        needMergePicker={true}
                        needTrim={true}
                        devType={handwritingType}
                        color={modeType.color||"#f30b01"}
                        mode={modeType.mode || "1"}
                        brush={modeType.brush||"xs"}
                        onEmSuccess={this.onHandWrittenEmSuccess}
                        inherit={true}
                        onChange={this.SignatureOnChange}
                    >
                        <Icon type={'sign'}/>
                        {(isEm && localExist) || (!isEm && (Object.keys(SignUtil.getVariableMapVal(handlewritingKey, {})).length > 0)) && <div className={'sign-icon-item-dot'}/>}
                    </Signature>
                    </div>
                    <div className={'sign-icon-item'} onClick={() => {
                        let updateParams = {};
                        updateParams[VariableKeys.SHOW_MORE_FUN] = !showAttachment;
                        updateParams[VariableKeys.SIGN_VOICE_ENTRY] = false;
                        updateParams[VariableKeys.SIGN_IMG_UPLOAD] = false;
                        batchControlVariableMap(updateParams)
                    }}>
                        <Icon style={{'color': showAttachment ? '#2DB7F5' : ''}} type={'tianjia'}/>
                        {this.showMoreDot() && <div className={'sign-icon-item-dot'}/>}
                    </div>
                </Flex>
                {this.getDisplayCom()}
            </div>
        )
    }

    getUploadCom(){
        const {wfSignInputStore} = this.props;
        const {isForwad,batchControlVariableMap} = wfSignInputStore;
        const signImgUpload = SignUtil.getVariableMapVal(VariableKeys.SIGN_IMG_UPLOAD, false);
        const imgKey = isForwad ? VariableKeys.FORWARD_SIGN_IMAGE : VariableKeys.SIGN_IMAGE;
        let imgages = SignUtil.getVariableMapVal(imgKey, []);
        const fileUploading = SignUtil.getVariableMapVal(VariableKeys.SIGN_FILE_UPLOADING,false);
        return (
            <div className={'sign-icon-item'} key={'signImgUpload'}>
                {(imgages.length > 0  && !fileUploading) ?
                    <Icon onClick={() => {
                        let updateParams = {};
                        updateParams[VariableKeys.SHOW_MORE_FUN] = false;
                        updateParams[VariableKeys.SIGN_VOICE_ENTRY] = false;
                        updateParams[VariableKeys.SIGN_IMG_UPLOAD] = !signImgUpload;
                        batchControlVariableMap(updateParams);
                    }} style={{'color': signImgUpload ? '#2DB7F5' : ''}} type={'blog-tupian'}/>
                    :
                    <Upload onChange={(ids, datas) => {
                        let variableParams = {};
                        variableParams[imgKey] = imgages.concat(datas);
                        SignUtil.doSignInputChange({}, variableParams);
                    }}
                            onUploading={(type) => SignUtil.onUploading(type,'iconbtn')}
                            multiSelection={true}
                            uploadUrl={'/api/doc/upload/uploadFile'}
                            listType="img"
                            limitType="jpg,jpeg,png"
                    >
                        <Icon type={'blog-tupian'}/>
                    </Upload>
                }
                {imgages.length > 0 && <div className={'sign-icon-item-dot'}/>}
            </div>
        )
    }

    getDisplayCom() {
        const {wfSignInputStore} = this.props;
        const {variableMap, remarkWfStore, remarkDocStore, positionStore, isForwad, reqOperators = [], atUserStore} = wfSignInputStore;
        const wfReplaceDataKey = isForwad ? VariableKeys.FORWARD_SIGN_WF_REPLACE_DATAS : VariableKeys.SIGN_WF_REPLACE_DATAS;
        const docReplaceDataKey = isForwad ? VariableKeys.FORWARD_SIGN_DOC_REPLACE_DATAS : VariableKeys.SIGN_DOC_REPLACE_DATAS;
        const signworkflowreplacedata = SignUtil.getVariableMapVal(wfReplaceDataKey, []);
        const signdocreplacedata = SignUtil.getVariableMapVal(docReplaceDataKey, []);

        const template2 = {
            default: {
                theme: 'col2_row2',
                dataKeys: ['data', 'jobtitlename', 'subcompanyname', 'departmentname'],
            },
        };

        return (
            <div style={{'display': 'none'}}>
                <Browser
                    store={remarkWfStore}
                    hasAdvanceSerach
                    type={16}
                    isSingle={false}
                    onChange={(ids, name, datas) => {
                        const variableParams = {};
                        variableParams[wfReplaceDataKey] = datas;
                        SignUtil.doSignInputChange({}, variableParams);
                    }}
                    valueArray={signworkflowreplacedata}
                />
                <Browser
                    store={remarkDocStore}
                    hasAdvanceSerach
                    type={37}
                    isSingle={false}
                    onChange={(ids, name, datas) => {
                        const variableParams = {};
                        variableParams[docReplaceDataKey] = datas;
                        SignUtil.doSignInputChange({}, variableParams);
                    }}
                    valueArray={signdocreplacedata}
                />
                <AtSomeone
                    datas={mobx.toJS(reqOperators)}
                    template={template2}
                    store={atUserStore}
                    onOk={(datas = []) => {
                        let r = [];
                        datas && datas.map((item) => {
                            r.push(` @${item.data.replace(/\(/g,'（').replace(/\)/g,'）')} `);
                        })
                        SignUtil.appendRemark(r.join(''));
                    }}
                    imgSrcDataKey={'icon'}
                    nameDataKey={'data'}
                />
            </div>
        )
    }

    onHandWrittenEmSuccess=(res)=>{
        const { saveSignAnnex, isForwad, controlVariableMap,variableMap } = this.props.wfSignInputStore;
        if(typeof res =="string"){
            res = JSON.parse(res);
        }
        const { localData = '' } = res;
        const handlewritingKey = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;

        if(localData){
            let param={url:`data:image/png;base64,`+localData}
            saveSignAnnex(3, JSON.stringify(param));
            controlVariableMap("localExist",true)
        }else{
            variableMap.delete(handlewritingKey)
            controlVariableMap("localExist",false)
        }
    }

    SignatureOnChange = (result, mode) => {
        const { saveSignAnnex, isForwad, controlVariableMap } = this.props.wfSignInputStore;
        const { changeSubmitParam } = base.wfOperateStore;
        let key  = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN+"_datasAndUrls" : VariableKeys.SIGN_HANDWRITTEN+"_datasAndUrls";
        const handlewritingKey = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;
        let key_fileid = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;
        if(result.isEmpty == true){
            controlVariableMap(key, result)
            controlVariableMap(key_fileid, [])
        }else{
            result.modeType = mode;
            let _result = JSON.stringify(result);
            controlVariableMap(key, result)
            saveSignAnnex(3, _result)
        }
        changeSubmitParam(SignUtil.getSignInfoDatas());
    }

    showMoreDot(){
        const {wfSignInputStore} = this.props;
        const {isForwad} = wfSignInputStore;
        const annexdocinfoKey = isForwad ? VariableKeys.FORWARD_SIGN_ANNEX_DOC_INFOS : VariableKeys.SIGN_ANNEX_DOC_INFOS;
        const wfDataKey = isForwad ? VariableKeys.FORWARD_SIGN_WF_REPLACE_DATAS : VariableKeys.SIGN_WF_REPLACE_DATAS;
        const docDataKey = isForwad ? VariableKeys.FORWARD_SIGN_DOC_REPLACE_DATAS : VariableKeys.SIGN_DOC_REPLACE_DATAS;
        const fulltextannotationKey = isForwad ? VariableKeys.FORWARD_SIGN_FULL_TEXT_ANNOTATION : VariableKeys.SIGN_FULL_TEXT_ANNOTATION;
        const soundResourceDataKey = isForwad ? VariableKeys.FORWARD_SIGN_SPEECH_ATTCHMENT_DATAS : VariableKeys.SIGN_SPEECH_ATTCHMENT_DATAS;
        const remarkLocationKey = isForwad ? VariableKeys.FORWARD_REMARK_LOCATION : VariableKeys.SIGN_REMARK_LOCATION;
        const handlewritingKey = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;
        const localExist = SignUtil.getVariableMapVal("localExist", false)
        const wfOperateStore = base.wfOperateStore;
        const { markInfo = {}, } = wfOperateStore;
        const {remarkInfo={}}=markInfo;
        const {handwritingType="h5"}=remarkInfo;
        const isEm = handwritingType=="em"&&(window.em&&window.em.checkJsApi&&window.em.checkJsApi("handleWriting"));
        // let isShowHandWrittenDot = false;
        // if((isEm && localExist) || (!isEm && (Object.keys(SignUtil.getVariableMapVal(handlewritingKey, {})).length > 0))){
        //     isShowHandWrittenDot=true;
        // }
        if (SignUtil.getVariableMapVal(annexdocinfoKey, []).length > 0) return true;
        if (SignUtil.getVariableMapVal(wfDataKey, []).length > 0) return true;
        if (SignUtil.getVariableMapVal(docDataKey, []).length > 0) return true;
        // if (isShowHandWrittenDot) return true;
        if (Object.keys(SignUtil.getVariableMapVal(remarkLocationKey, {})).length > 0) return true;
        if (SignUtil.getVariableMapVal(soundResourceDataKey, []).length > 0) return true;
        if (SignUtil.getVariableMapVal(fulltextannotationKey, []).length > 0) return true;
        return false;
    }
}

export default IconBtnsList
